package com.prawn.search.service;

import com.prawn.search.pojo.Post;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

@Service
public class PostService {
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    /**
     * 按点击量倒序排序分页搜索
     * @param key
     * @param page
     * @param size
     * @return
     */
    public Page<Post> clickNumQuery(String key, int page, int size) {
        int status = 1;
        Pageable pageable = PageRequest.of(page-1,size);
        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.boolQuery()
                        .must(QueryBuilders.matchQuery(key,"title"))
                        .must(QueryBuilders.termQuery("state", status))
                ).withPageable(pageable)
                .withSort(SortBuilders.fieldSort("clickNum").order(SortOrder.DESC))
                .build();

        return elasticsearchTemplate.queryForPage(searchQuery, Post.class);
    }

    /**
     * 按创建时间倒序排序分页搜索
     * @param key
     * @param page
     * @param size
     * @return
     */
    public Page<Post> timeQuery(String key, int page, int size) {
        Pageable pageable = PageRequest.of(page-1, size);
        int status = 1;
        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.boolQuery()
                        .must(QueryBuilders.termQuery("state",status))
                        .must(QueryBuilders.matchQuery(key,"title")))
                .withPageable(pageable).withSort(SortBuilders.fieldSort("creationTime").order(SortOrder.DESC))
                .build();

        return elasticsearchTemplate.queryForPage(searchQuery, Post.class);
    }
}
